﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Linq.Expressions;
using Platform.Storage.Entity;

namespace System.Linq
{
	public static class QueryableExtensions
	{


		public static IQueryable<TData> EagerLoad<TData, TReturn>( this IQueryable<TData> query, Expression<Func<TData, TReturn>> getter )
		{
			var dynQuery = query as EntityDynamicQuery<TData>;

			if ( dynQuery == null )
			{
				return query;
			}
			else
			{
				dynQuery.LoadProperties.Add( getter.GetPropertyName() );
				return dynQuery;
			}
		}


		public static IQueryable<TData> Apply<TData>( this IQueryable<TData> query, IQueryStrategy<TData> strategy, params IQueryStrategy<TData>[] moreStrategies )
		{
			if ( query != null && strategy != null )
			{
				var newQuery = strategy.Configure( query );

				if ( moreStrategies != null )
					moreStrategies.Each( s => newQuery = s.Configure( newQuery ) );

				return newQuery;
			}
			else
			{
				Debug.WriteLineIf( query == null, "Nenhuma query foi definida para aplicar as configurações." );
				Debug.WriteLineIf( strategy == null, "Nenhum configuração foi definida para a query." );

				return query;
			}
		}
	}


	public interface IQueryStrategy<TData>
	{
		IQueryable<TData> Configure( IQueryable<TData> query );
	}


}
